﻿using Microsoft.SharePoint;
using System.Web;
using System;
using System.IO;

namespace hzWeb.Layouts.hzWeb
{
    public partial class UserPhoto: IHttpHandler
    {
        #region IHttpHandler Members
 
        public bool IsReusable
        {
            get { return true; }
        }
 
        public void ProcessRequest(HttpContext context)
        {
            string alias = context.Request.QueryString["alias"];  
            var photo = SPContext.Current.Site.RootWeb.GetFile("SiteCollectionImages/" + alias + ".png");
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {                                    
                    byte[] photoBytes = null;
                    if (!photo.Exists)
                    {
                        // photo = SPContext.Current.Site.RootWeb.GetFile("_layouts/PersonPlaceholder.png");
                        photoBytes = this.DownloadFile(SPContext.Current.Web.Url + "/_layouts/PersonPlaceholder.png");
                    }
                    else
                    {
                        photoBytes = this.DownloadFile(photo.Web.Url + "/" + photo.Url);
                    }
                    // context.Response.Write(SPContext.Current.Web.Url);                

                    context.Response.ContentType = "image/png";
                    context.Response.OutputStream.Write(photoBytes, 0, photoBytes.Length);
                    context.Response.OutputStream.Flush();
                    //context.Response.End();
                }
                catch (Exception ex)
                {
                    context.Response.Write(ex.Message);
                    context.Response.Write("<br>");
                    context.Response.Write(ex.StackTrace);
                }
          });
        }

        private byte[] DownloadFile(string url)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.UseDefaultCredentials = true;
            byte[] data = wc.DownloadData(url);
            return data;
        }
 
        #endregion
    }
}
